package com.cc.handler;

import com.cc.model.entity.InventoryAlert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author CC
 * @version 1.0
 * @description: 库存预警WebSocket处理器
 * @date 2025/10/16 8:42
 */
@Component
public class InventoryWebSocketHandler extends TextWebSocketHandler {
    /**
     * 存储所有连接的WebSocketSession
     */
    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    /**
     * 当WebSocket连接建立成功时调用
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("WebSocket连接建立: " + session.getId());
    }

    /**
     * 当WebSocket连接关闭时调用
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("WebSocket连接关闭: " + session.getId());
    }

    /**
     * 向所有连接的客户端发送库存预警消息
     */
    public void sendInventoryAlert(InventoryAlert alert) {
        String message;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            message = mapper.writeValueAsString(alert);
        } catch (Exception e) {
            message = "{\"type\":\"ERROR\",\"message\":\"消息序列化失败\"}";
        }

        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    System.err.println("发送WebSocket消息失败: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 获取当前连接的客户端数量
     */
    public int getConnectedClients() {
        return sessions.size();
    }
}
